/*
 * @Author: scl
 * @Date: 2023-08-23 22:26:12
 * @LastEditTime: 2023-08-25 09:47:49
 * @Description: file content
 */
/*
 * @lc app=leetcode.cn id=43 lang=typescript
 *
 * [43] 字符串相乘
 *
 * https://leetcode.cn/problems/multiply-strings/description/
 *
 * algorithms
 * Medium (44.36%)
 * Likes:    1256
 * Dislikes: 0
 * Total Accepted:    309.9K
 * Total Submissions: 698.5K
 * Testcase Example:  '"2"\n"3"'
 *
 * 给定两个以字符串形式表示的非负整数 num1 和 num2，返回 num1 和 num2 的乘积，它们的乘积也表示为字符串形式。
 * 
 * 注意：不能使用任何内置的 BigInteger 库或直接将输入转换为整数。
 * 
 * 
 * 
 * 示例 1:
 * 
 * 
 * 输入: num1 = "2", num2 = "3"
 * 输出: "6"
 * 
 * 示例 2:
 * 
 * 
 * 输入: num1 = "123", num2 = "456"
 * 输出: "56088"
 * 
 * 
 * 
 * 提示：
 * 
 * 
 * 1 <= num1.length, num2.length <= 200
 * num1 和 num2 只能由数字组成。
 * num1 和 num2 都不包含任何前导零，除了数字0本身。
 * 
 * 
 */

// @lc code=start
function multiply(num1: string, num2: string): string {
    if (num1 == '0' || num2 == '0')
        return "0";
    const len1 = num1.length, len2 = num2.length, result = [], codeForZero = '0'.charCodeAt(0);
    let temp = 0;
    for (let j = len2 - 1; j >= 0; j--) {
        let index = result.length - len2 + j
        const n = num2.charCodeAt(j) - codeForZero
        for (let i = len1 - 1; i >= 0; i--) {
            const m = num1.charCodeAt(i) - codeForZero;
            let pro = m * n
            temp = pro % 10 + temp
            if (index >= 0 && temp + result[index] > 9) {
                temp += result[index]
                result[index] = temp % 10
                temp = ~~(pro / 10) + ~~(temp / 10)
            } else if (index >= 0) {
                result[index] = temp + result[index]
                temp = ~~(pro / 10)
            }
            if (index >= 0) index--
            else {
                if (temp > 9) {
                    result.unshift(temp - 10)
                    temp = ~~(pro / 10) + 1
                } else {
                    result.unshift(temp)
                    temp = ~~(pro / 10)
                }


            }
            if (i == 0 && temp) {
                result.unshift(temp)
                temp = 0
            }

        }
    }
    return result.join('');
}
// @lc code=end

